<template>
  <!--  搜索框组件-->
    <TableSearch  :deletSome="deletSomes"  @addRow="addUser" @deletSome="deletSomeUsers"  :search-fields="searchFields"  @search="handleSearch"  @reset="handleReset"></TableSearch>
    <!-- 表格组件 -->
    <TableComponent
        :columns="columns"
        :tableData="tableData"
        :loading="loading"
        :deletSome="deletSomes"
        @delete="handleDelete"
        @editRow="editUserRow"
        @somedelete="handleSomeDelete"
    />
    <pagination  :current-page="currentPage"  :page-size="pageSize"  :total="total"   @size-change="handleSizeChange"
   @current-change="handleCurrentChange"></pagination>
  </template>
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  
  import pagination from '@/components/pagination/index.vue';
  import TableSearch from '@/components/TableSearch/ordersearch.vue';
  import TableComponent from '@/components/DataTable/ordertable.vue';
  
  import api from '@/api/order'
  import router from "@/router/index.js";
  import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
  
  // 侧边栏折叠状态
  const sidebarCollapsed = ref(false);
  
  let deletSomes= true;
  // 搜索字段
  const searchFields = reactive([
    { label: '客户名称', prop: 'username', type: 'input' },
    { label: '订单编号', prop: 'orderNumber', type: 'input' },
    { label: '订单状态', prop: 'paymentStatus', type: 'select', options: [
        { label: '代付款', value: '代付款' },
        { label: '已完成', value: '已完成' },
        { label: '无效订单', value: '无效订单' },
      ]},
  ]);

  // 表格列定义
  const columns = [
    { prop: 'orderId', label: '订单id', width: 80 },
    { prop: 'orderNumber', label: '订单编号', width: 120 },
     { prop: 'users.username', label: '客户名称', width: 120 },
    { prop: 'coursesVo.courseName', label: '课程', width: 180 },
    { prop: 'coursesVo.teachers.teacherName', label: '讲师', width: 180 },
    { prop: 'paymentAmount', label: '支付金额', width: 120 },
    { prop: 'paymentStatus', label: '订单状态', width: 300 },
    { prop: 'createTime', label: '订单创建时间', width: 180 },
  ];
  
  // 表格数据
  const tableData = ref([]);
  const loading = ref(false);
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  const teacherId = JSON.parse(localStorage.getItem("token")).teacherId;
  let users;
  const Search =ref({})
  // 加载表格数据
  const loadData = async () => {
    loading.value = true;
  
    try {
      let datas
      Search.value.pageNum = currentPage.value;
      Search.value.pageSize = pageSize.value;
      Search.value.teacherId = teacherId;
      console.log(Search.value);
      // const response = await api.selectAll(Search.value);
      const response = await api.selectAll(Search.value);
  console.log('订单'+JSON.stringify(response.data))
      tableData.value = response.data.list || [];
      total.value = response.data.total || 0;
      console.log('加载数据成功:', response);
      if (response.code == 200) {
        // 开发环境调试日志
      } else {
        // API返回了错误码
        throw new Error(response.message || '获取数据失败');
      }
    } catch (error) {
      console.error('加载数据失败:', error);
      // 友好的错误提示
      ElMessage.error({
        message: error.message || '加载数据失败，请稍后重试',
        duration: 3000
      });
  
      // 重置数据防止显示旧数据
      tableData.value = [];
      total.value = 0;
    } finally {
      loading.value = false;
    }
  };
  function addUser() {
    router.push(`/user/create`);
  }
  // 批量删除
  async function deletSomeUsers() {
    try {
      // 确认对话框
      const confirmResult = await ElMessageBox.confirm(
          '确定要批量删除这些订单吗？此操作不可撤销！',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      );
  
      if (confirmResult !== 'confirm') {
        return; // 用户点击了取消
      }
  
      // 极速模式：所有删除请求同时发起
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在批量删除订单...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
  
      const results = await Promise.allSettled(
          Object.values(users).map(user =>
              api.delete({ id: user.orderId })
                  .then(() => ({ status: 'fulfilled', id: user.orderId }))
                  .catch(error => ({ status: 'rejected', id: user.orderId, error }))
          )
      );
  
      // 关闭加载动画
      loadingInstance.close();
  
      // 生成统计报告
      const successCount = results.filter(r => r.status === 'fulfilled').length;
      const failedCount = results.filter(r => r.status === 'rejected').length;
  
      // 刷新数据
      await loadData();
  
      // 显示操作结果
      if (failedCount === 0) {
        ElMessage.success(`成功删除 ${successCount} 个订单`);
      } else if (successCount === 0) {
        ElMessage.error(`删除失败，所有 ${failedCount} 个订单均未删除成功`);
      } else {
        ElMessage.warning(
            `删除完成，成功 ${successCount} 个，失败 ${failedCount} 个`,
            { duration: 5000 }
        );
      }
  
      return {
        total: results.length,
        success: successCount,
        failed: failedCount,
        errors: results.filter(r => r.status === 'rejected').map(r => ({
          orderId: r.orderId,
          error: r.error.message
        }))
      };
  
    } catch (error) {
      // 用户可能点击了取消按钮，不需要处理
      if (error !== 'cancel' && error !== 'close') {
        ElMessage.error(`删除操作出错: ${error.message}`);
      }
      return null;
    }
  }
  
  function editUserRow(row) {
    router.push(`/user/${row.orderId}/edit`);
    // sessionStorage.setItem("user",JSON);
  }
  // 处理搜索
  const handleSearch = (params) => {
    console.log('Search params:', params);
    currentPage.value = 1;
    Search.value = params;
    loadData();
  };
  
  // 处理重置
  const handleReset = () => {
    Search.value={}
    currentPage.value = 1;
    loadData();
  };
  
  // 删除功能
  const handleDelete = async (row) => {
    // 极速模式：所有删除请求同时发起
    try {
      await ElMessageBox.confirm(
        `确定要删除订单 "${row.orderNumber}" (ID: ${row.orderId}) 吗？`,
          '删除确认',
          {
            confirmButtonText: '确认删除',
            cancelButtonText: '取消',
            type: 'warning',
            closeOnClickModal: false, // 防止误点
            beforeClose: async (action, instance, done) => {
              if (action === 'confirm') {
                instance.confirmButtonLoading = true;
                try {
                  const loadingInstance = ElLoading.service({
                    lock: true,
                    text: '正在删除订单...',
                    background: 'rgba(0, 0, 0, 0.7)'
                  });
  
                  await api.delete({ id: row.orderId });
                  done();
                  // 关闭加载动画
                  loadingInstance.close();
                } catch (error) {
                  instance.confirmButtonLoading = false;
                  // 关闭加载动画
                  loadingInstance.close();
                  throw error;
                }
              } else {
                done();
              }
            }
          }
      );
  
      // 删除成功后刷新数据
      await loadData();
  
      ElMessage({
        type: 'success',
        message: `订单 "${row.orderNumber}" 删除成功`,
        duration: 3000
      });
  
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage({
          type: 'error',
          message: `删除失败: ${error.message || '未知错误'}`,
          duration: 5000
        });
      } else {
        ElMessage({
          type: 'info',
          message: '已取消删除操作',
          duration: 2000
        });
      }
    }
  };
  function handleSomeDelete(rows) {
     users=rows;
     console.log(rows,"获取多列的值")
  }
  // 处理每页数量变化
  const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    loadData();
  };
  
  // 处理页码变化
  const handleCurrentChange = (newPage) => {
    currentPage.value = newPage;
    loadData();
  };
  function deleteclick() {
  
  }
  // 初始化加载数据
  onMounted(() => {
    loadData();
  });
  </script>
  
  <style scoped>
  #app {
    font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
    min-height: 100vh;
  }
  </style>
  